const transport = require('../../utils/email');
const { EMAIL, MAXCOUNT } = require('../../config/constants');
const { VerifyCode: vcode } = require('../../models/system/verifycode');
const logger = require('../../utils/logger');

class EmailService {
  
    // 发送验证码邮件
    static async sendVerificationCode(email) {
        try {
            logger.info(`开始发送验证码邮件至: ${email}`);
            
            // 检查发送次数
            const count = await vcode.countDocuments({
                scene: 'register',
                receiver: email,
            });
            if (count >= MAXCOUNT) {
                const errorMsg = '已发送验证码次数超过最大次数，请稍后重试';
                logger.warn(`发送验证码失败: ${errorMsg}, 接收者: ${email}`);
                throw new Error(errorMsg);
            }
            
            // 检查是否已存在未过期的验证码
            const existingCode = await vcode.findOne({
                scene: 'register',
                receiver: email,
                used: false
            });
            if (existingCode) {
                const errorMsg = '已发送验证码，请稍后重试,有效期2分钟,2分钟后再次发送';
                logger.warn(`发送验证码失败: ${errorMsg}, 接收者: ${email}`);
                throw new Error(errorMsg);
            }
            
            // 生成验证码
            const code = Math.floor(Math.random() * 1000000);
            logger.info(`生成验证码: ${code} for ${email}`);
            
            // 保存验证码
            const verifyCode = {
                receiver: email,
                scene: 'register',
                used: false,
                code: code.toString()
            };
            
            // 创建邮件选项
            const options = {
                from: EMAIL,
                to: email,
                subject: '验证码',
                text: `您的验证码是: ${code}`
            };
            
            // 保存验证码并发送邮件
            await vcode.create(verifyCode);
            logger.info(`验证码已保存到数据库: ${email}`);
            
            await transport.sendMail(options);
            logger.info(`验证码邮件发送成功: ${email}`);
        } catch (error) {
            logger.error(`发送验证码失败: ${error.message}, 接收者: ${email}`);
            throw new Error(`发送验证码失败: ${error.message}`);
        }
    }

    // // 发送通知邮件
    // static async sendNotification(email, title, content) {
    //     // 实现发送通知邮件的逻辑
    // }

    // 验证邮箱验证码
    static async verifyCode(email, code) {
        try {
            logger.info(`开始验证验证码: ${code} for ${email}`);
            
            const verifyCode = await vcode.findOne({
                receiver: email,
                scene: 'register',
                used: false,
                code: code.toString()
            });
            
            if (!verifyCode) {
                const errorMsg = '验证码不存在或已过期';
                logger.warn(`验证码验证失败: ${errorMsg}, 接收者: ${email}, 验证码: ${code}`);
                throw new Error(errorMsg);
            }
            
            // 更新验证码状态为已使用
            await vcode.updateOne({ _id: verifyCode._id }, { $set: { used: true } });
            logger.info(`验证码验证成功: ${email}, 验证码: ${code}`);
            
            return true;
        } catch (error) {
            logger.error(`验证码验证失败: ${error.message}, 接收者: ${email}, 验证码: ${code}`);
            throw new Error(`验证码验证失败: ${error.message}`);
        }
    }
}

module.exports = EmailService;